// pages/main/me/setting/changePhone/chagnePhone.js
var intervalFef;
let util;
let originPhone;
let newPhoneNum, msgCode, oldPhone;
Page({

  data: {
    hidePhoneNum: "",
    lessTime: 0,
    btnEnable: false
  },


  onLoad: function (options) {
    newPhoneNum = "";
    msgCode = "";
    oldPhone = "";
    util = getApp().require("/utils/util.js");
    originPhone = getApp().globalData.userInfo.phoneNumber
    this.setData({
      hidePhoneNum: originPhone.substring(0, 3) + "****" + originPhone.substring(7, 11)
    })
  },

  inputNewPhone: function (e) {
    newPhoneNum = e.detail.value
    this.isBtnEnable();
  },
  inputMsgCode: function (e) {
    msgCode = e.detail.value;
    this.isBtnEnable();
  },
  inputOldPhone: function (e) {
    oldPhone = e.detail.value;
    this.isBtnEnable();
  },

  getMsgCode: function (e) {
    if (!util.checkPhoneNumber(newPhoneNum)) return;

    if (this.data.lessTime > 0) return;

    getApp().$http.getMsgCodeByChangePhone(newPhoneNum).then(res => {
      wx.showToast({
        title: '验证码发送成功',
        icon: 'none'
      })
      this.data.lessTime = 60;
      intervalFef = setInterval(this.countTime, 1000);
    })
  },

  isBtnEnable: function () {
    if (newPhoneNum.length > 0 && msgCode.length > 0 && oldPhone.length > 0) {
      this.setData({
        btnEnable: true
      })
    } else {

      this.setData({
        btnEnable: false
      })
    }
  },

  tapOK: function () {
    if (!this.data.btnEnable) return;
    if (!util.checkPhoneNumber(oldPhone)) return;
    if (!util.checkPhoneNumber(newPhoneNum)) return;

    if (originPhone != oldPhone) {
      wx.showToast({
        title: '原手机号不正确',
        icon: 'none'
      })
      return;
    }

    let data = {
      newPhoneNumber: newPhoneNum,
      oldPhoneNumber: oldPhone,
      verificationCode: msgCode
    }

    getApp().$http.changePhone(data).then(res => {
      wx.showToast({
        title: '换绑成功',
        duration: 1000,
      })

      setTimeout(() => {
        wx.navigateBack({
          delta: 1,
        })
      }, 1000);
    });

  },

  countTime: function () {
    if (this.data.lessTime == 0) {
      intervalFef = clearInterval(intervalFef);
      return;
    }
    this.data.lessTime--;
    this.setData({
      lessTime: this.data.lessTime
    });
  },
  onUnload: function () {
    if (intervalFef) {
      clearInterval(intervalFef);
    }
  },

})